// src/mocks/clientApi.js

// Mock Data based on database design
const mockUsers = [
  {
    user_id: 1,
    user_name: 'client1',
    password: 'password123',
    real_name: '张三',
    user_type: 0, // 0 为客户
    company: 'ABC公司',
    phone: '13800001111',
    status: 1, // 1=正常
  },
  {
    user_id: 2,
    user_name: 'client2',
    password: 'password123',
    real_name: '李四',
    user_type: 0,
    company: 'XYZ公司',
    phone: '13900002222',
    status: 1,
  },
];

const mockMeetingRooms = [
  {
    room_id: 101,
    room_name: '会议室A',
    room_type: 1, // 1=教室
    capacity: 10,
    projector: 1, // 1正常
    sound: 1, // 1正常
    internet: 1, // 1正常
    price: 100,
    availability_time: '2025-05-28 00:00:00', // Example, actual availability would be dynamic
    status: 1, // 1=空闲
    status2: 0, // 0为未使用
  },
  {
    room_id: 102,
    room_name: '会议室B',
    room_type: 2, // 2=圆桌
    capacity: 8,
    projector: 1,
    sound: 0, // 0不正常
    internet: 1,
    price: 80,
    availability_time: '2025-05-28 00:00:00',
    status: 1,
    status2: 0,
  },
  {
    room_id: 103,
    room_name: '会议室C',
    room_type: 3, // 3=董事会
    capacity: 20,
    projector: 1,
    sound: 1,
    internet: 1,
    price: 200,
    availability_time: '2025-05-28 00:00:00',
    status: 3, // 3=预定
    status2: 1, // 1为使用
  },
];

let mockOrders = [ // Use let because orders will be modified
  {
    order_id: 1,
    user_id: 1,
    room_id: 101,
    start_time: '2025-06-01 09:00:00',
    end_time: '2025-06-01 10:00:00',
    create_time: '2025-05-20 10:00:00',
    cancel_time: null,
    status: 1, // 1为有效
    payment_status: 2, // 2为已支付
    total_fee: 100,
    refund_fee: 0,
    cancellation_status: 0, // 0: No cancellation requested, 1: Pending approval, 2: Approved, 3: Rejected
  },
  {
    order_id: 2,
    user_id: 1,
    room_id: 102,
    start_time: '2025-05-25 14:00:00',
    end_time: '2025-05-25 16:00:00',
    create_time: '2025-05-18 09:00:00',
    cancel_time: null,
    status: 1,
    payment_status: 2,
    total_fee: 160,
    refund_fee: 0,
    cancellation_status: 0,
  },
  {
    order_id: 3,
    user_id: 2,
    room_id: 103,
    start_time: '2025-06-05 10:00:00',
    end_time: '2025-06-05 12:00:00',
    create_time: '2025-05-22 11:00:00',
    cancel_time: null,
    status: 1,
    payment_status: 1, // 1为未支付
    total_fee: 400,
    refund_fee: 0,
    cancellation_status: 0,
  },
  {
    order_id: 4,
    user_id: 1,
    room_id: 101,
    start_time: '2025-05-20 10:00:00',
    end_time: '2025-05-20 11:00:00',
    create_time: '2025-05-15 09:00:00',
    cancel_time: '2025-05-18 09:00:00',
    status: 2, // 2为无效 (已取消)
    payment_status: 2,
    total_fee: 100,
    refund_fee: 100,
    cancellation_status: 2, // Approved
  },
];

const mockComments = [
  {
    comment_id: 1,
    order_id: 2,
    comment_time: '2025-05-26 10:00:00',
    content: '会议室B很不错，就是音响有点问题。',
    rating: 4,
    reply_id: null,
    comment_type: 1,
  },
];

const mockMaintenanceRecords = [
  {
    maintenance_id: 1,
    user_id: 1, // Assuming employee user_id
    room_id: 102,
    create_time: '2025-05-26 11:00:00',
    update_time: '2025-05-27 09:00:00',
    start_time: '2025-05-27 09:00:00',
    end_time: null,
    problem_desc: '会议室B音响故障，无声音输出。',
    status: '2', // 2 进行中
  },
];

// Helper to parse date strings
const parseDateTime = (dtString) => new Date(dtString.replace(' ', 'T'));
const formatDateTime = (date) => date.toISOString().replace('T', ' ').substring(0, 19);

/**
 * @typedef {object} Booking
 * @property {number} order_id - 订单的唯一标识
 * @property {number} user_id - 关联用户表 user_id（客户）
 * @property {number} room_id - 关联会议室表 room_id
 * @property {string} start_time - 预订开始时间（精确到小时）
 * @property {string} end_time - 预订结束时间（精确到小时）
 * @property {string} create_time - 订单创建时间（当前时间）
 * @property {string | null} cancel_time - 订单取消时间（当前时间）
 * @property {number} status - 订单状态（1为有效 2为无效）
 * @property {number} payment_status - 支付状态（1为未支付 2为已支付）
 * @property {number} total_fee - 计算订单总金额
 * @property {number} refund_fee - 退款金额
 * @property {number} cancellation_status - 取消状态 (0: No request, 1: Pending, 2: Approved, 3: Rejected)
 * @property {string} room_name - 会议室名称 (joined from mockMeetingRooms)
 */

/**
 * @typedef {object} CancellationRequest
 * @property {number} order_id - 订单的唯一标识
 * @property {number} user_id - 关联用户表 user_id（客户）
 * @property {string} user_name - 客户用户名
 * @property {string} real_name - 客户真实姓名
 * @property {number} room_id - 关联会议室表 room_id
 * @property {string} room_name - 会议室名称
 * @property {string} start_time - 预订开始时间
 * @property {string} end_time - 预订结束时间
 * @property {number} total_fee - 订单总金额
 * @property {number} refund_fee - 预估退款金额
 * @property {string} request_time - 申请取消时间
 * @property {number} cancellation_status - 取消状态 (1: Pending approval)
 */

/**
 * @typedef {object} MeetingRoom
 * @property {number} room_id - 会议室唯一标识
 * @property {string} room_name - 会议室名称
 * @property {number} room_type - 会议室类型（1=教室 2=圆桌 3=董事会 4=多媒体）
 * @property {number} capacity - 会议室座位数(最大容纳人数)
 * @property {number} projector - 会议室投影仪（0 不正常 1正常）
 * @property {number} sound - 会议室音响（0 不正常 1正常）
 * @property {number} internet - 会议室网络（0 不正常 1正常）
 * @property {number} price - 会议室租赁价格（按每小时计算）
 * @property {string} availability_time - 会议室可用时间
 * @property {number} status - 会议室状态1 (1=空闲, 2=锁定, 3=预定, 4=维护)
 * @property {number} status2 - 会议室状态2 （0为未使用 1为使用）
 */

/**
 * @typedef {object} BookingConfirmation
 * @property {number} order_id - 新生成的订单ID
 * @property {number} room_id - 预订的会议室ID
 * @property {number} user_id - 预订用户ID
 * @property {string} start_time - 预订开始时间
 * @property {string} end_time - 预订结束时间
 * @property {number} total_fee - 订单总金额
 * @property {number} status - 订单状态 (2=锁定)
 * @property {number} payment_status - 支付状态 (1=未支付)
 * @property {string} payment_due_time - 支付截止时间
 */

/**
 * @typedef {object} PaymentResult
 * @property {number} order_id - 支付的订单ID
 * @property {boolean} success - 支付是否成功
 * @property {string} message - 支付结果消息
 * @property {number} payment_status - 支付状态 (1=未支付, 2=已支付)
 * @property {number} order_status - 订单状态 (1=有效, 2=无效)
 */

/**
 * @typedef {object} RefundPolicyItem
 * @property {number} hours_before_start - 距离开始时间的小时数
 * @property {number} refund_percentage - 退款百分比
 * @property {string} description - 退款规则描述
 */

/**
 * @typedef {object} RefundPolicyResult
 * @property {boolean} success - 操作是否成功
 * @property {string} message - 消息
 * @property {Array<RefundPolicyItem>} data - 退款规则列表
 */

/**
 * 模拟获取取消预订的退费规则
 * @returns {Promise<RefundPolicyResult>}
 */
export const fetchRefundPolicy = async () => {
  console.log('Mock API: Fetching refund policy');
  const policy = [
    { hours_before_start: 72, refund_percentage: 100, description: '提前 72 小时退全款' },
    { hours_before_start: 48, refund_percentage: 75, description: '提前 48 小时退 75%' },
    { hours_before_start: 24, refund_percentage: 25, description: '提前 24 小时退 25%' },
  ];
  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: 'Refund policy fetched successfully',
    data: policy,
  }), 300));
};

/**
 * @typedef {object} CancellationResult
 * @property {number} order_id - 取消的订单ID
 * @property {boolean} success - 取消是否成功
 * @property {string} message - 取消结果消息
 * @property {number} order_status - 订单状态 (2=无效)
 * @property {number} refund_fee - 实际退款金额
 */

/**
 * @typedef {object} CancellationRequestPayload
 * @property {number} order_id - 订单ID
 * @property {number} user_id - 用户ID
 */

/**
 * @typedef {object} CancellationRequestResponse
 * @property {boolean} success - 操作是否成功
 * @property {string} message - 消息
 * @property {number} order_id - 订单ID
 * @property {number} cancellation_status - 取消状态 (1: Pending approval)
 * @property {number} refund_fee_estimate - 预估退款金额
 */

/**
 * @typedef {object} ApproveCancellationResponse
 * @property {boolean} success - 操作是否成功
 * @property {string} message - 消息
 * @property {number} order_id - 订单ID
 * @property {number} cancellation_status - 取消状态 (2: Approved, 3: Rejected)
 * @property {number} order_status - 订单状态 (1: Valid, 2: Invalid)
 * @property {number} refund_fee - 实际退款金额 (if approved)
 */

/**
 * @typedef {object} ConfirmCancellationCompletionPayload
 * @property {number} order_id - 订单ID
 * @property {number} user_id - 用户ID
 */

/**
 * @typedef {object} ConfirmCancellationCompletionResponse
 * @property {boolean} success - 操作是否成功
 * @property {string} message - 消息
 * @property {number} order_id - 订单ID
 * @property {number} cancellation_status - 取消状态 (3: Completed)
 * @property {number} order_status - 订单状态 (2: Invalid)
 */

/**
 * 模拟获取用户即将到来的预订
 * @param {number} userId - 用户ID
 * @returns {Promise<Array<Booking>>}
 */
export const fetchUpcomingBookings = async (userId) => {
  console.log(`Mock API: Fetching upcoming bookings for user ${userId}`);
  const now = new Date();
  const bookings = mockOrders
    .filter(
      (order) =>
        order.user_id === userId &&
        order.status === 1 && // 有效订单
        order.payment_status === 2 && // 已支付
        parseDateTime(order.end_time) > now // 结束时间在当前时间之后
    )
    .map((order) => {
      const room = mockMeetingRooms.find((r) => r.room_id === order.room_id);
      return {
        ...order,
        room_name: room ? room.room_name : '未知会议室',
      };
    });
  return new Promise((resolve) => setTimeout(() => resolve(bookings), 500));
};

/**
 * 模拟获取用户过去的预订
 * @param {number} userId - 用户ID
 * @returns {Promise<Array<Booking>>}
 */
export const fetchPastBookings = async (userId) => {
  console.log(`Mock API: Fetching past bookings for user ${userId}`);
  const now = new Date();
  const bookings = mockOrders
    .filter(
      (order) =>
        order.user_id === userId &&
        order.status === 1 && // 有效订单
        order.payment_status === 2 && // 已支付
        parseDateTime(order.end_time) <= now // 结束时间在当前时间之前或等于
    )
    .map((order) => {
      const room = mockMeetingRooms.find((r) => r.room_id === order.room_id);
      return {
        ...order,
        room_name: room ? room.room_name : '未知会议室',
      };
    });
  return new Promise((resolve) => setTimeout(() => resolve(bookings), 500));
};

/**
 * 模拟获取用户所有订单
 * @param {number} userId - 用户ID
 * @returns {Promise<Array<Booking>>}
 */
export const fetchAllBookings = async (userId) => {
  console.log(`Mock API: Fetching all bookings for user ${userId}`);
  const bookings = mockOrders
    .filter((order) => order.user_id === userId)
    .map((order) => {
      const room = mockMeetingRooms.find((r) => r.room_id === order.room_id);
      return {
        ...order,
        room_name: room ? room.room_name : '未知会议室',
      };
    });
  return new Promise((resolve) => setTimeout(() => resolve(bookings), 500));
};

/**
 * 模拟筛选和获取可用会议室
 * @param {string} date - 日期 (YYYY-MM-DD)
 * @param {string} startTime - 开始时间 (HH:MM:SS)
 * @param {string} endTime - 结束时间 (HH:MM:SS)
 * @param {number} capacity - 参会人数
 * @param {string[]} requiredEquipment - 所需设备数组 (e.g., ["projector", "sound", "internet"])
 * @returns {Promise<Array<MeetingRoom>>}
 */
export const searchMeetingRooms = async (date, startTime, endTime, capacity, requiredEquipment) => {
  console.log(`Mock API: Searching rooms for ${date} ${startTime}-${endTime}, capacity ${capacity}, equipment: ${requiredEquipment.join(', ')}`);
  const requestedStart = parseDateTime(`${date} ${startTime}`);
  const requestedEnd = parseDateTime(`${date} ${endTime}`);

  const filteredRooms = mockMeetingRooms.filter((room) => {
    // 房间状态必须是空闲 (status=1) 且未使用 (status2=0)
    if (room.status !== 1 || room.status2 !== 0) {
      return false;
    }

    // 检查容量
    if (room.capacity < capacity) {
      return false;
    }

    // 检查所需设备
    if (requiredEquipment.includes('projector') && room.projector !== 1) return false;
    if (requiredEquipment.includes('sound') && room.sound !== 1) return false;
    if (requiredEquipment.includes('internet') && room.internet !== 1) return false;

    // 检查是否有订单与请求的时间段冲突
    const conflictingOrder = mockOrders.some((order) => {
      if (order.room_id === room.room_id && order.status === 1) { // 只考虑有效订单
        const orderStart = parseDateTime(order.start_time);
        const orderEnd = parseDateTime(order.end_time);

        // 检查时间段是否重叠
        return (
          (requestedStart < orderEnd && requestedEnd > orderStart)
        );
      }
      return false;
    });

    return !conflictingOrder;
  });

  return new Promise((resolve) => setTimeout(() => resolve(filteredRooms), 500));
};

/**
 * 模拟创建订单
 * @param {number} userId - 用户ID
 * @param {number} roomId - 会议室ID
 * @param {string} startTime - 预订开始时间 (YYYY-MM-DD HH:MM:SS)
 * @param {string} endTime - 预订结束时间 (YYYY-MM-DD HH:MM:SS)
 * @param {number} totalFee - 订单总金额
 * @returns {Promise<BookingConfirmation>}
 */
export const createBooking = async (userId, roomId, startTime, endTime, totalFee) => {
  console.log(`Mock API: Creating booking for user ${userId}, room ${roomId}`);
  const newOrderId = mockOrders.length > 0 ? Math.max(...mockOrders.map(o => o.order_id)) + 1 : 1;
  const createTime = formatDateTime(new Date());
  const paymentDueTime = formatDateTime(new Date(Date.now() + 30 * 60 * 1000)); // 30 minutes from now

  const newOrder = {
    order_id: newOrderId,
    user_id: userId,
    room_id: roomId,
    start_time: startTime,
    end_time: endTime,
    create_time: createTime,
    cancel_time: null,
    status: 2, // 2=锁定
    payment_status: 1, // 1=未支付
    total_fee: totalFee,
    refund_fee: 0,
  };
  mockOrders.push(newOrder);

  // Update room status to locked (status=2)
  const roomIndex = mockMeetingRooms.findIndex(r => r.room_id === roomId);
  if (roomIndex !== -1) {
    mockMeetingRooms[roomIndex].status = 2; // 锁定
  }

  return new Promise((resolve) => setTimeout(() => resolve({
    order_id: newOrderId,
    room_id: roomId,
    user_id: userId,
    start_time: startTime,
    end_time: endTime,
    total_fee: totalFee,
    status: 2, // 锁定
    payment_status: 1, // 未支付
    payment_due_time: paymentDueTime,
  }), 500));
};

/**
 * 模拟处理支付
 * @param {number} orderId - 订单ID
 * @param {number} paymentAmount - 支付金额
 * @param {string} paymentMethod - 支付方式 (e.g., "alipay", "wechatpay")
 * @param {boolean} success - 模拟支付成功或失败
 * @returns {Promise<PaymentResult>}
 */
export const processPayment = async (orderId, paymentAmount, paymentMethod, success = true) => {
  console.log(`Mock API: Processing payment for order ${orderId}, amount ${paymentAmount}, method ${paymentMethod}, success: ${success}`);
  const orderIndex = mockOrders.findIndex(o => o.order_id === orderId);
  if (orderIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      order_id: orderId,
      success: false,
      message: '订单不存在',
      payment_status: 1,
      order_status: 2,
    }), 500));
  }

  if (success) {
    mockOrders[orderIndex].payment_status = 2; // 已支付
    mockOrders[orderIndex].status = 1; // 有效 (预定成功)
    // Update room status to booked (status=3)
    const roomIndex = mockMeetingRooms.findIndex(r => r.room_id === mockOrders[orderIndex].room_id);
    if (roomIndex !== -1) {
      mockMeetingRooms[roomIndex].status = 3; // 预定
      mockMeetingRooms[roomIndex].status2 = 1; // 使用
    }
    return new Promise((resolve) => setTimeout(() => resolve({
      order_id: orderId,
      success: true,
      message: '支付成功',
      payment_status: 2,
      order_status: 1,
    }), 500));
  } else {
    mockOrders[orderIndex].payment_status = 1; // 未支付
    mockOrders[orderIndex].status = 2; // 无效 (订单取消)
    // Revert room status to idle (status=1)
    const roomIndex = mockMeetingRooms.findIndex(r => r.room_id === mockOrders[orderIndex].room_id);
    if (roomIndex !== -1) {
      mockMeetingRooms[roomIndex].status = 1; // 空闲
      mockMeetingRooms[roomIndex].status2 = 0; // 未使用
    }
    return new Promise((resolve) => setTimeout(() => resolve({
      order_id: orderId,
      success: false,
      message: '支付失败，订单已取消',
      payment_status: 1,
      order_status: 2,
    }), 500));
  }
};

/**
 * 模拟获取客户符合取消预订规则的会议室
 * 客户预订成功后，若放弃使用会议室，需要提前 24 小时申请取消预约。
 * @param {number} userId - 用户ID
 * @returns {Promise<Array<Booking>>}
 */
export const fetchCancellableBookings = async (userId) => {
  console.log(`Mock API: Fetching cancellable bookings for user ${userId}`);
  const now = new Date();
  const twentyFourHoursLater = new Date(now.getTime() + 24 * 60 * 60 * 1000); // Current time + 24 hours

  const bookings = mockOrders
    .filter(
      (order) =>
        order.user_id === userId &&
        order.status === 1 && // 有效订单
        order.payment_status === 2 && // 已支付
        order.cancellation_status === 0 && // 未申请取消
        parseDateTime(order.start_time) > twentyFourHoursLater // 开始时间在当前时间 + 24小时之后
    )
    .map((order) => {
      const room = mockMeetingRooms.find((r) => r.room_id === order.room_id);
      return {
        ...order,
        room_name: room ? room.room_name : '未知会议室',
      };
    });
  return new Promise((resolve) => setTimeout(() => resolve(bookings), 500));
};

/**
 * 模拟取消订单
 * @param {number} orderId - 订单ID
 * @param {number} userId - 用户ID
 * @param {number} userId - 用户ID
 * @returns {Promise<CancellationRequestResponse>}
 */
export const cancelBooking = async (orderId, userId) => {
  console.log(`Mock API: Cancelling booking for order ${orderId}, user ${userId}`);
  const orderIndex = mockOrders.findIndex(o => o.order_id === orderId && o.user_id === userId);

  if (orderIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      order_id: orderId,
      success: false,
      message: '订单不存在或不属于当前用户',
      cancellation_status: 0,
      refund_fee_estimate: 0,
    }), 500));
  }

  const order = mockOrders[orderIndex];
  if (order.status === 2) { // Already cancelled/invalid
    return new Promise((resolve) => setTimeout(() => resolve({
      order_id: orderId,
      success: false,
      message: '订单已是无效状态',
      cancellation_status: order.cancellation_status,
      refund_fee_estimate: order.refund_fee,
    }), 500));
  }
  if (order.cancellation_status !== 0) { // Already has a cancellation request
    return new Promise((resolve) => setTimeout(() => resolve({
      order_id: orderId,
      success: false,
      message: '该订单已有取消申请，请勿重复提交。',
      cancellation_status: order.cancellation_status,
      refund_fee_estimate: order.refund_fee,
    }), 500));
  }

  const now = new Date();
  const startTime = parseDateTime(order.start_time);
  const timeDiffHours = (startTime.getTime() - now.getTime()) / (1000 * 60 * 60); // Difference in hours

  let refundPercentage = 0;
  if (timeDiffHours >= 72) {
    refundPercentage = 100;
  } else if (timeDiffHours >= 48) {
    refundPercentage = 75;
  } else if (timeDiffHours >= 24) {
    refundPercentage = 25;
  } else {
    // If less than 24 hours, no refund
    refundPercentage = 0;
  }

  const refundAmount = order.total_fee * (refundPercentage / 100);

  // Set cancellation status to pending approval
  order.cancellation_status = 1; // 1: Pending approval
  order.cancel_time = formatDateTime(now); // Record request time
  order.refund_fee = refundAmount; // Store calculated refund amount

  // Do NOT change order.status or room status here. This happens upon employee approval.

  return new Promise((resolve) => setTimeout(() => resolve({
    order_id: orderId,
    success: true,
    message: '取消预订申请已提交，等待员工审核。',
    cancellation_status: 1, // Pending approval
    refund_fee_estimate: refundAmount,
  }), 500));
};


/**
 * 模拟获取所有待审核的取消预订申请
 * @returns {Promise<{success: boolean, message: string, data: Array<CancellationRequest>}>}
 */
export const fetchPendingCancellations = async () => {
  console.log('Mock API: Fetching pending cancellation requests');
  const pendingRequests = mockOrders
    .filter(order => order.cancellation_status === 1) // 1: Pending approval
    .map(order => {
      const user = mockUsers.find(u => u.user_id === order.user_id);
      const room = mockMeetingRooms.find(r => r.room_id === order.room_id);
      return {
        order_id: order.order_id,
        user_id: order.user_id,
        user_name: user ? user.user_name : '未知用户',
        real_name: user ? user.real_name : '未知姓名',
        room_id: order.room_id,
        room_name: room ? room.room_name : '未知会议室',
        start_time: order.start_time,
        end_time: order.end_time,
        total_fee: order.total_fee,
        refund_fee: order.refund_fee,
        request_time: order.cancel_time, // This is the time the client requested cancellation
        cancellation_status: order.cancellation_status,
      };
    });
  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: 'Pending cancellation requests fetched successfully',
    data: pendingRequests,
  }), 500));
};

/**
 * 模拟员工审核通过取消预订申请
 * @param {number} orderId - 订单ID
 * @returns {Promise<ApproveCancellationResponse>}
 */
export const approveCancellation = async (orderId) => {
  console.log(`Mock API: Approving cancellation for order ${orderId}`);
  const orderIndex = mockOrders.findIndex(o => o.order_id === orderId);

  if (orderIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '订单不存在',
      order_id: orderId,
      cancellation_status: null,
      order_status: null,
      refund_fee: 0,
    }), 500));
  }

  const order = mockOrders[orderIndex];
  if (order.cancellation_status !== 1) { // Not pending approval
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '该订单不在待审核取消状态',
      order_id: orderId,
      cancellation_status: order.cancellation_status,
      order_status: order.status,
      refund_fee: order.refund_fee,
    }), 500));
  }

  order.cancellation_status = 2; // 2: Approved
  order.status = 2; // 2: 无效 (订单已取消)
  order.cancel_time = formatDateTime(new Date()); // Update cancel_time to approval time

  // Revert room status to idle (status=1)
  const roomIndex = mockMeetingRooms.findIndex(r => r.room_id === order.room_id);
  if (roomIndex !== -1) {
    mockMeetingRooms[roomIndex].status = 1; // 空闲
    mockMeetingRooms[roomIndex].status2 = 0; // 未使用
  }

  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: `订单 ${orderId} 取消已批准，退款金额 ¥${order.refund_fee.toFixed(2)}`,
    order_id: orderId,
    cancellation_status: 2,
    order_status: 2,
    refund_fee: order.refund_fee,
  }), 500));
};

/**
 * 模拟员工审核拒绝取消预订申请
 * @param {number} orderId - 订单ID
 * @returns {Promise<{success: boolean, message: string, order_id: number, cancellation_status: number, order_status: number}>}
 */
export const rejectCancellation = async (orderId) => {
  console.log(`Mock API: Rejecting cancellation for order ${orderId}`);
  const orderIndex = mockOrders.findIndex(o => o.order_id === orderId);

  if (orderIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '订单不存在',
      order_id: orderId,
      cancellation_status: null,
      order_status: null,
    }), 500));
  }

  const order = mockOrders[orderIndex];
  if (order.cancellation_status !== 1) { // Not pending approval
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '该订单不在待审核取消状态',
      order_id: orderId,
      cancellation_status: order.cancellation_status,
      order_status: order.status,
    }), 500));
  }

  order.cancellation_status = 3; // 3: Rejected
  // Order status remains 1 (valid) and room status remains unchanged

  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: `订单 ${orderId} 取消申请已被拒绝。`,
    order_id: orderId,
    cancellation_status: 3,
    order_status: order.status, // Remains valid
  }), 500));
};


/**
 * 模拟客户确认取消预订完成
 * @param {number} orderId - 订单ID
 * @param {number} userId - 用户ID
 * @returns {Promise<ConfirmCancellationCompletionResponse>}
 */
export const confirmCancellationCompletion = async (orderId, userId) => {
  console.log(`Mock API: Confirming cancellation completion for order ${orderId}, user ${userId}`);
  const orderIndex = mockOrders.findIndex(o => o.order_id === orderId && o.user_id === userId);

  if (orderIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '订单不存在或不属于当前用户',
      order_id: orderId,
      cancellation_status: null,
      order_status: null,
    }), 500));
  }

  const order = mockOrders[orderIndex];
  if (order.cancellation_status !== 2) { // Not approved (pending client confirmation)
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '该订单不在待客户确认取消完成状态',
      order_id: orderId,
      cancellation_status: order.cancellation_status,
      order_status: order.status,
    }), 500));
  }

  order.cancellation_status = 3; // 3: Completed
  // The order status (status=2) and room status (status=1, status2=0) should already be set by approveCancellation

  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: `订单 ${orderId} 已确认取消完成。`,
    order_id: orderId,
    cancellation_status: 3,
    order_status: order.status, // Should be 2 (invalid)
  }), 500));
};


/**
 * @typedef {object} RoomStatusOverview
 * @property {number} room_id - 会议室ID
 * @property {string} room_name - 会议室名称
 * @property {number} status - 会议室状态 (1=空闲, 2=锁定, 3=预定, 4=维护)
 * @property {object | null} current_booking - 当前正在进行的预订信息，如果空闲则为null
 * @property {number} [current_booking.order_id]
 * @property {string} [current_booking.start_time]
 * @property {string} [current_booking.end_time]
 * @property {string} [current_booking.user_name]
 */

/**
 * @typedef {object} RoomTimelineSlot
 * @property {string} start_time - 时间段开始时间
 * @property {string} end_time - 时间段结束时间
 * @property {string} status - 时间段状态 (idle, booked, in-use, maintenance)
 * @property {number | null} order_id - 关联订单ID
 * @property {string | null} user_name - 预订用户名称
 */

/**
 * @typedef {object} RoomDailyTimeline
 * @property {number} room_id - 会议室ID
 * @property {string} room_name - 会议室名称
 * @property {string} date - 查询日期 (YYYY-MM-DD)
 * @property {Array<RoomTimelineSlot>} timeline_slots - 当天的时间轴列表
 */

/**
 * @typedef {object} UpdateBookingStatusResponse
 * @property {boolean} success - 操作是否成功
 * @property {string} message - 消息
 * @property {number} order_id - 订单ID
 * @property {number} order_status - 订单状态
 * @property {number} room_status - 会议室状态1
 * @property {number} room_status2 - 会议室状态2
 */

/**
 * @typedef {object} CompleteBookingResponse
 * @property {boolean} success - 操作是否成功
 * @property {string} message - 消息
 * @property {number} order_id - 订单ID
 * @property {number} order_status - 订单状态
 * @property {number} room_status - 会议室状态1
 * @property {number} room_status2 - 会议室状态2
 * @property {number} [maintenance_id] - 如果进入维护状态，则返回维修记录ID
 */

/**
 * @typedef {object} CompleteMaintenanceResponse
 * @property {boolean} success - 操作是否成功
 * @property {string} message - 消息
 * @property {number} maintenance_id - 维修记录ID
 * @property {number} maintenance_status - 维修状态 (3: 已完成)
 * @property {number} room_id - 关联会议室ID
 * @property {number} room_status - 会议室状态1
 * @property {number} room_status2 - 会议室状态2
 */

/**
 * 模拟获取所有会议室当前时间段的状态概览
 * @returns {Promise<{success: boolean, message: string, data: Array<RoomStatusOverview>}>}
 */
export const fetchRoomCurrentStatus = async () => {
  console.log('Mock API: Fetching all meeting room current statuses');
  const now = new Date();
  const currentStatuses = mockMeetingRooms.map(room => {
    const currentBooking = mockOrders.find(order =>
      order.room_id === room.room_id &&
      order.status === 1 && // Valid order
      order.payment_status === 2 && // Paid
      parseDateTime(order.start_time) <= now &&
      parseDateTime(order.end_time) > now
    );

    let bookingInfo = null;
    if (currentBooking) {
      const user = mockUsers.find(u => u.user_id === currentBooking.user_id);
      bookingInfo = {
        order_id: currentBooking.order_id,
        start_time: currentBooking.start_time,
        end_time: currentBooking.end_time,
        user_name: user ? user.real_name : '未知用户',
      };
    }

    return {
      room_id: room.room_id,
      room_name: room.room_name,
      status: room.status,
      current_booking: bookingInfo,
    };
  });

  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: 'Meeting room current statuses fetched successfully.',
    data: currentStatuses,
  }), 500));
};

/**
 * 模拟获取特定会议室某一天的所有时间段状态
 * @param {number} roomId - 会议室ID
 * @param {string} date - 查询日期 (YYYY-MM-DD)
 * @returns {Promise<{success: boolean, message: string, data: RoomDailyTimeline}>}
 */
export const fetchRoomDailyTimeline = async (roomId, date) => {
  console.log(`Mock API: Fetching daily timeline for room ${roomId} on ${date}`);
  const room = mockMeetingRooms.find(r => r.room_id === roomId);
  if (!room) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '会议室不存在。',
      data: null,
    }), 500));
  }

  const timelineSlots = [];
  const startOfDay = parseDateTime(`${date} 00:00:00`);
  const endOfDay = parseDateTime(`${date} 23:59:59`);

  // Generate 24 hourly slots
  for (let i = 0; i < 24; i++) {
    const slotStart = new Date(startOfDay);
    slotStart.setHours(i);
    const slotEnd = new Date(slotStart);
    slotEnd.setHours(i + 1);

    let slotStatus = 'idle';
    let slotOrderId = null;
    let slotUserName = null;

    // Check for bookings in this slot
    const bookingInSlot = mockOrders.find(order => {
      const orderStart = parseDateTime(order.start_time);
      const orderEnd = parseDateTime(order.end_time);
      return (
        order.room_id === roomId &&
        order.status !== 2 && // Not cancelled/invalid
        order.payment_status === 2 && // Paid
        slotStart < orderEnd && slotEnd > orderStart
      );
    });

    if (bookingInSlot) {
      const user = mockUsers.find(u => u.user_id === bookingInSlot.user_id);
      slotOrderId = bookingInSlot.order_id;
      slotUserName = user ? user.real_name : '未知用户';

      const now = new Date();
      if (parseDateTime(bookingInSlot.start_time) <= now && parseDateTime(bookingInSlot.end_time) > now) {
        slotStatus = 'in-use'; // Currently in use
      } else {
        slotStatus = 'booked'; // Booked for future
      }
    }

    // Check for maintenance in this slot
    const maintenanceInSlot = mockMaintenanceRecords.find(record => {
      const recordStart = parseDateTime(record.start_time);
      const recordEnd = record.end_time ? parseDateTime(record.end_time) : new Date(8640000000000000); // Max date if end_time is null
      return (
        record.room_id === roomId &&
        record.status !== '3' && // Not completed
        slotStart < recordEnd && slotEnd > recordStart
      );
    });

    if (maintenanceInSlot) {
      slotStatus = 'maintenance';
      slotOrderId = null; // No order during maintenance
      slotUserName = null;
    }

    timelineSlots.push({
      start_time: formatDateTime(slotStart),
      end_time: formatDateTime(slotEnd),
      status: slotStatus,
      order_id: slotOrderId,
      user_name: slotUserName,
    });
  }

  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: 'Meeting room daily timeline fetched successfully.',
    data: {
      room_id: room.room_id,
      room_name: room.room_name,
      date: date,
      timeline_slots: timelineSlots,
    },
  }), 500));
};

/**
 * 模拟员工将客户预定的会议室设置为使用状态
 * @param {number} orderId - 订单ID
 * @param {number} employeeId - 员工ID
 * @returns {Promise<UpdateBookingStatusResponse>}
 */
export const updateBookingStatusToInUse = async (orderId, employeeId) => {
  console.log(`Mock API: Setting booking ${orderId} to in-use by employee ${employeeId}`);
  const orderIndex = mockOrders.findIndex(o => o.order_id === orderId);
  if (orderIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '订单不存在。',
      order_id: orderId,
      order_status: null,
      room_status: null,
      room_status2: null,
    }), 500));
  }

  const order = mockOrders[orderIndex];
  const roomIndex = mockMeetingRooms.findIndex(r => r.room_id === order.room_id);

  if (order.status !== 1 || order.payment_status !== 2) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '订单状态不正确，无法设置为使用中。',
      order_id: orderId,
      order_status: order.status,
      room_status: mockMeetingRooms[roomIndex]?.status,
      room_status2: mockMeetingRooms[roomIndex]?.status2,
    }), 500));
  }

  // Assuming "预定" (status 3) means it's ready to be used, and "使用中" is a logical state
  // For mock, we'll keep order.status as 1 (valid) but update room.status2 to 1 (in use)
  if (roomIndex !== -1) {
    mockMeetingRooms[roomIndex].status2 = 1; // 1为使用
  }

  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: `订单 ${orderId} 状态已更新为使用中，会议室状态已更新。`,
    order_id: orderId,
    order_status: order.status,
    room_status: mockMeetingRooms[roomIndex]?.status,
    room_status2: mockMeetingRooms[roomIndex]?.status2,
  }), 500));
};

/**
 * 模拟员工完成客户预订并设置会议室状态（空闲或维护）
 * @param {number} orderId - 订单ID
 * @param {number} employeeId - 员工ID
 * @param {boolean} isRoomNormal - 会议室是否正常 (true: 空闲, false: 维护)
 * @param {string} [problemDesc] - 故障描述 (isRoomNormal为false时必填)
 * @returns {Promise<CompleteBookingResponse>}
 */
export const completeBookingAndSetRoomStatus = async (orderId, employeeId, isRoomNormal, problemDesc = null) => {
  console.log(`Mock API: Completing booking ${orderId} and setting room status by employee ${employeeId}`);
  const orderIndex = mockOrders.findIndex(o => o.order_id === orderId);
  if (orderIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '订单不存在。',
      order_id: orderId,
      order_status: null,
      room_status: null,
      room_status2: null,
    }), 500));
  }

  const order = mockOrders[orderIndex];
  const roomIndex = mockMeetingRooms.findIndex(r => r.room_id === order.room_id);
  if (roomIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '关联会议室不存在。',
      order_id: orderId,
      order_status: order.status,
      room_status: null,
      room_status2: null,
    }), 500));
  }

  // Mark order as completed (status remains 1, but conceptually completed)
  // In a real system, you might have a 'completed' status for orders.
  // For now, we'll just update room status.

  if (isRoomNormal) {
    mockMeetingRooms[roomIndex].status = 1; // 1=空闲
    mockMeetingRooms[roomIndex].status2 = 0; // 0为未使用
    return new Promise((resolve) => setTimeout(() => resolve({
      success: true,
      message: `订单 ${orderId} 已完成，会议室已设置为空闲。`,
      order_id: orderId,
      order_status: order.status,
      room_status: 1,
      room_status2: 0,
    }), 500));
  } else {
    if (!problemDesc) {
      return new Promise((resolve) => setTimeout(() => resolve({
        success: false,
        message: '请提供故障描述。',
        order_id: orderId,
        order_status: order.status,
        room_status: mockMeetingRooms[roomIndex].status,
        room_status2: mockMeetingRooms[roomIndex].status2,
      }), 500));
    }
    mockMeetingRooms[roomIndex].status = 4; // 4=维护
    mockMeetingRooms[roomIndex].status2 = 0; // 0为未使用

    // Create a new maintenance record
    const newMaintenanceId = mockMaintenanceRecords.length > 0 ? Math.max(...mockMaintenanceRecords.map(m => m.maintenance_id)) + 1 : 1;
    const createTime = formatDateTime(new Date());
    const newMaintenanceRecord = {
      maintenance_id: newMaintenanceId,
      user_id: employeeId, // Employee who reported/set to maintenance
      room_id: order.room_id,
      create_time: createTime,
      update_time: createTime,
      start_time: createTime, // Maintenance starts now
      end_time: null,
      problem_desc: problemDesc,
      status: '2', // 2 进行中
    };
    mockMaintenanceRecords.push(newMaintenanceRecord);

    return new Promise((resolve) => setTimeout(() => resolve({
      success: true,
      message: `订单 ${orderId} 已完成，会议室已设置为维护状态，并创建维修记录。`,
      order_id: orderId,
      order_status: order.status,
      room_status: 4,
      room_status2: 0,
      maintenance_id: newMaintenanceId,
    }), 500));
  }
};

/**
 * 模拟员工完成会议室维修并设置为空闲状态
 * @param {number} maintenanceId - 维修记录ID
 * @param {number} employeeId - 员工ID
 * @returns {Promise<CompleteMaintenanceResponse>}
 */
export const completeMaintenanceAndSetRoomIdle = async (maintenanceId, employeeId) => {
  console.log(`Mock API: Completing maintenance ${maintenanceId} by employee ${employeeId}`);
  const maintenanceIndex = mockMaintenanceRecords.findIndex(m => m.maintenance_id === maintenanceId);
  if (maintenanceIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '维修记录不存在。',
      maintenance_id: maintenanceId,
      maintenance_status: null,
      room_id: null,
      room_status: null,
      room_status2: null,
    }), 500));
  }

  const maintenanceRecord = mockMaintenanceRecords[maintenanceIndex];
  const roomIndex = mockMeetingRooms.findIndex(r => r.room_id === maintenanceRecord.room_id);
  if (roomIndex === -1) {
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '关联会议室不存在。',
      maintenance_id: maintenanceId,
      maintenance_status: maintenanceRecord.status,
      room_id: maintenanceRecord.room_id,
      room_status: null,
      room_status2: null,
    }), 500));
  }

  if (maintenanceRecord.status === '3') { // Already completed
    return new Promise((resolve) => setTimeout(() => resolve({
      success: false,
      message: '该维修记录已是完成状态。',
      maintenance_id: maintenanceId,
      maintenance_status: maintenanceRecord.status,
      room_id: maintenanceRecord.room_id,
      room_status: mockMeetingRooms[roomIndex].status,
      room_status2: mockMeetingRooms[roomIndex].status2,
    }), 500));
  }

  maintenanceRecord.status = '3'; // 3 已完成
  maintenanceRecord.end_time = formatDateTime(new Date());
  maintenanceRecord.update_time = formatDateTime(new Date());

  mockMeetingRooms[roomIndex].status = 1; // 1=空闲
  mockMeetingRooms[roomIndex].status2 = 0; // 0为未使用

  return new Promise((resolve) => setTimeout(() => resolve({
    success: true,
    message: `维修记录 ${maintenanceId} 已完成，会议室已设置为空闲。`,
    maintenance_id: maintenanceId,
    maintenance_status: 3,
    room_id: maintenanceRecord.room_id,
    room_status: 1,
    room_status2: 0,
  }), 500));
};

// Export mock data for potential direct use or inspection
export { mockUsers, mockMeetingRooms, mockOrders, mockComments, mockMaintenanceRecords };
